//
//  NSString+HJDeviceRegister.m
//  project
//
//  Created by hu on 2019/4/1.
//  Copyright © 2019 健健. All rights reserved.
//

#import "NSString+HJDeviceRegister.h"
#import <AdSupport/AdSupport.h>
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (HJDeviceRegister)

#pragma mark - 获取UUID 并保存在钥匙串
+ (NSString *)getUUIDByKeyChain {
    NSString*strUUID = (NSString*)[self load:DeviceID];
    if([strUUID isEqualToString:@""]|| !strUUID) {
        strUUID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        if(strUUID.length ==0 || [strUUID isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
            //生成一个uuid的方法
            CFUUIDRef uuidRef= CFUUIDCreate(kCFAllocatorDefault);
            strUUID = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,uuidRef));
            strUUID = [self md5:strUUID];
            CFRelease(uuidRef);
        } else {
            strUUID = [self md5:strUUID];
        }
        [self save:DeviceID data:strUUID];
    }
    return strUUID;
}

+ (nullable NSString *)md5:(nullable NSString *)str {
    if (!str) return nil;
    
    const char *cStr = str.UTF8String;
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    NSMutableString *md5Str = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
        [md5Str appendFormat:@"%02x", result[i]];
    }
    return md5Str;
}

+ (NSMutableDictionary*)getKeychainQuery:(NSString*)service {
    return[NSMutableDictionary dictionaryWithObjectsAndKeys:
           (id)kSecClassGenericPassword,(id)kSecClass,
           service,(id)kSecAttrService,
           service,(id)kSecAttrAccount,
           (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
           nil];
}

+ (void)save:(NSString*)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data]forKey:(id)kSecValueData];
    SecItemAdd((CFDictionaryRef)keychainQuery,NULL);
}

+ (id)load:(NSString*)service {
    id ret =nil;
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData =NULL;
    if(SecItemCopyMatching((CFDictionaryRef)keychainQuery,(CFTypeRef*)&keyData) ==noErr){
        @try{
            ret =[NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData*)keyData];
        }@catch(NSException *e) {
            NSLog(@"Unarchiveof %@ failed: %@",service, e);
        }@finally{
        }
    }
    if(keyData)
        CFRelease(keyData);
    return ret;
}

/**
 删除Keychain里的缓存唯一标识
 @param service Key值
 */
+ (void)deleteKeyData:(NSString*)service {
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}
@end
